using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using StudentVideo.Binders;
using StudentVideo.Data;
using StudentVideo.Extensions;
using StudentVideo.Filters;
using StudentVideo.Helper;
using StudentVideo.Middleware;
using StudentVideo.Utils;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options => {
   options.AddPolicy("CustomPolicy", policy => {
      policy.WithOrigins("http://localhost:3001")
            .WithMethods("GET", "POST", "PUT", "DELETE", "OPTION")
            .WithHeaders("Content-Type", "Authorization");
   });
});

builder.Services.AddRedisDb(builder.Configuration);
builder.Services.AddScoped(sp => {
   return new RedisDbHelper(sp.GetRequiredService<StackExchange.Redis.IDatabase>(), sp.GetRequiredService<ILogger<RedisDbHelper>>());
});

builder.Services.AddHttpContextAccessor();
builder.Services.AddAntiforgery();

builder.Services.AddCustomServices();
builder.Services.AddCustomInterceptors();
builder.Services.AddCustomDatabase(builder.Configuration);

builder.Services.AddScoped<JwtHelper>();

// 控制器过滤器
builder.Services
   .AddScoped<CustomAuthorizationFilter>() // 全局过滤器
   .AddControllers(options => {
      options.Filters.Add<CustomAuthorizationFilter>();
      options.Filters.Add<CustomActionFilter>();
      options.Filters.Add<CustomExceptionFilter>();
      options.Filters.Add<HttpResultFilter>();
      options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
      options.Filters.Add(new AllowAnonymousFilter());

      options.ModelBinderProviders.Insert(0, new CurrentUserBinderProvider());
   });

builder.Services.AddRouting(options => {
   options.LowercaseUrls = true;
});
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());

builder.Services.AddCustomAuthentication(builder.Configuration);

builder.Services.AddOpenApiSwagger();

var app = builder.Build();

app.UseCors("CustomPolicy");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
   app.UseDeveloperExceptionPage();

   // 配置 Swagger JSON 文件的路径
   app.UseSwagger(c => {
      c.RouteTemplate = "docs/{documentName}/swagger.json";
   });
   // 配置 Swagger UI 的路由前缀
   app.UseSwaggerUI(c => {
      c.SwaggerEndpoint("/docs/v1/swagger.json", "StudentVideo API V1");
      c.RoutePrefix = "docs";
   });

} else {
   app.UseExceptionHandler("/Error", true);
   app.UseHsts();
}

app.UseStaticFiles();
app.UseRouting();

// 使用工厂方法注册中间件
app.Use(next => {
   ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
   ILogger logger = loggerFactory.CreateLogger("Logger");
   return new RequestLoggingMiddleware(next, logger).InvokeAsync;
});

app.UseAuthentication();
app.UseAuthorization();

app.UseAntiforgery();

// 配置API路由
app.MapControllers();

// 初始化数据库
using (var scope = app.Services.CreateScope()) {
   var services = scope.ServiceProvider;
   try {
      var context = services.GetRequiredService<AppDbContext>();
      var redis = services.GetRequiredService<RedisDbHelper>();

      InitializerHelper initializerHelper = new(context, redis);
      await initializerHelper.Invoke();

   } catch (Exception ex) {
      var logger = services.GetRequiredService<ILogger<Program>>();
      logger.LogError(ex, "初始化数据库时发生错误");
   }
}

app.Run();
